﻿using B.MESUI.Login.WareHouseManage.Dtos;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace B.MESUI.Login.WareHouseManage.WareHouseLocation
{
    public partial class CreateWareHouseLocationForm : DevExpress.XtraEditors.XtraForm
    {
        public delegate void LocationLoadDelegate();
        public event LocationLoadDelegate LocationLoad;
        public CreateWareHouseLocationForm()
        {
            InitializeComponent();
        }

        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            //点击保存按钮触发保存方法 调用后端post请求添加仓库位置信息
            // 获取用户输入
            string locationCode = textEdit1.Text.Trim(); // 假设你有这个控件
            string locationName = textEdit2.Text.Trim();
            string warehouseAreaId = gridLookUpEdit1.EditValue?.ToString();
            string remark = textEdit3.Text.Trim();

            // 非空验证
            if (string.IsNullOrEmpty(locationCode))
            {
                MessageBox.Show("位置编码不能为空");
                return;
            }
            if (string.IsNullOrEmpty(locationName))
            {
                MessageBox.Show("位置名称不能为空");
                return;
            }
            if (string.IsNullOrEmpty(warehouseAreaId))
            {
                MessageBox.Show("所属库区不能为空");
                return;
            }

            // 构造请求体对象
            var model = new LocationModel
            {
                locationid = locationCode,
                locationname = locationName,
                areaid = warehouseAreaId,
                locationdesc = remark
            };

            // 序列化为 JSON
            string jsonContent = JsonConvert.SerializeObject(model);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            // 发起 POST 请求
            using (var client = new HttpClient())
            {
                try
                {
                    var response = await client.PostAsync("http://39.103.49.30:9981/api/Location/CreateLOCATIONMODEL", content);

                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("保存成功！");
                        this.DialogResult = DialogResult.OK;
                        this.Close(); // 关闭当前窗口
                        //这里使用委托获取父窗体的刷新方法
                        LocationLoad.Invoke();
                    }
                    else
                    {
                        string errorText = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"保存失败: {errorText}");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                }
            }
        }

        public async Task LoadWarehousesAsync()
        {
            using (var client = new HttpClient())
            {
                try
                {
                    var response = await client.GetAsync("http://39.103.49.30:9981/api/Area/GetWarehouseAreaIdAndName");

                    if (response.IsSuccessStatusCode)
                    {
                        string json = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<ApiResultStandard<AreaIdAndName>>(json);

                        // 绑定数据到 GridLookUpEdit
                        gridLookUpEdit1.Properties.DataSource = result.ResultData;
                        gridLookUpEdit1.Properties.ValueMember = "id";
                        gridLookUpEdit1.Properties.DisplayMember = "areaname";

                        // 配置视图 - 这是关键修复点！
                        // 获取或创建 GridView
                        GridView view = gridLookUpEdit1.Properties.View as GridView;
                        if (view == null)
                        {
                            view = new GridView();
                            gridLookUpEdit1.Properties.View = view;
                        }

                        // 清除现有列
                        view.Columns.Clear();

                        // 添加列：仓库名称
                        view.Columns.Add(new GridColumn()
                        {
                            FieldName = "areaname",
                            Caption = "库区名称",
                            Visible = true
                        });

                        // 添加列：仓库ID（可选）
                        view.Columns.Add(new GridColumn()
                        {
                            FieldName = "id",
                            Caption = "库区ID",
                            Visible = false // 隐藏ID列
                        });

                        // 设置最佳列宽
                        view.BestFitColumns();

                        // 默认选中第一个
                        if (result.ResultData.Count > 0)
                            gridLookUpEdit1.EditValue = null;
                    }
                    else
                    {
                        MessageBox.Show("无法加载库区信息");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                }
            }
        }

        private void CreateWareHouseLocationForm_Load(object sender, EventArgs e)
        {
            LoadWarehousesAsync();
        }
    }
}